<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider v-model:collapsed="collapsed" collapsible theme="light">
      <div class="logo">
        <transition name="el-fade-in">
          <div class="transition-box" v-show="collapsed == false">
            <a-image
                :width="100"
                style="margin-left: 32px; margin-top: 4px"
                src="/q3.png"
            />
          </div>
        </transition>
        <transition name="el-fade-in">
          <div class="transition-box" v-show="collapsed == true">
            <a-image
                :width="60"
                style="margin-left: -10px; margin-top: 0px;"
                src="/logo.png"
            />
          </div>
        </transition>

      </div>
      <a-menu v-model:selectedKeys="selectedKeys" theme="light" mode="inline">
        <a-menu-item key="FirstOrderSet" @click="goOrderFirstVisit">
          <span>
            <heart-outlined style="color: deeppink"/>
            <span>开始咨询</span>
          </span>
        </a-menu-item>
        <a-menu-item key="timeSet" @click="goVisitManage">
          <span>
            <bulb-outlined style="color: green"/>
            <span>初访预约记录</span>
          </span>
        </a-menu-item>
        <a-menu-item key="dutySet" @click="goConsultRecord">
          <span>
            <cloud-outlined style="color: lightsalmon"/>
            <span>咨询访问记录</span>
          </span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>

    <a-layout>
      <div>
        <a-layout-header style="
          background: #fff;
          padding: 0;
          box-shadow: 1px 1px 1px #888888;
          height: 70px;
        " bordered>
          <div style="display:table;width: 100%;vertical-align: middle;height: 70px">
            <div style="
          height: 70px;
          display:table-cell;word-wrap: break-word;
          ">
              <a-page-header style="border: none;width:78%;position: absolute;margin-bottom: 23.5px" title="学生"
                             sub-title="here is student"/>
            </div>
            <div class="myop" style="
          width:16%;
          display:table-cell;
          height:70px;
          word-wrap: break-word;

          ">
              <a-menu mode="horizontal" @select="selectCurrUser">
                <a-sub-menu>
                  <template #title>
                    <a-avatar v-if="currImageUrl" @click="setAvatar" :src="currImageUrl"
                              style="vertical-align: middle"/>
                    <span v-else style="vertical-align: middle;
                    cursor: pointer">
                      <smile-outlined/>
                      <a @click="setAvatar" style="font-size: 14px; color: #aa0000">
                        设置头像
                      </a>
                    </span>
                    <span>&nbsp;&nbsp;</span>
                    <span style="vertical-align: middle">{{ currUser.userId }}
                      <b v-if="currUser.userName" style="color:#0458a7;">[
                        {{ currUser.userName }}
                      ]</b>
                    </span>
                  </template>
                  <a-menu-item key="password">密码修改</a-menu-item>
                  <a-menu-item key="exit">退出系统</a-menu-item>
                </a-sub-menu>
              </a-menu>
            </div>
          </div>
        </a-layout-header>
      </div>


      <a-modal v-model:visible="visible" title="设置新头像" @ok="execUpload" style="width:1000px">
        <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
                  :before-upload="() => false" @change="handleChange" @preview="handlePreview">

          <a-avatar v-if="imageUrl" @click="setAvatar" :src="imageUrl" shape="circle" style="vertical-align: middle"
                    :size="118"/>
          <!-- <img :src="imageUrl" /> -->
          <div v-else>
            <plus-outlined/>
            <div class="ant-upload-text">选择图片或拖动至此处</div>
          </div>
        </a-upload>
        <!--
        <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal> -->
      </a-modal>


      <a-layout-content style="margin-top:16px">
        <router-view></router-view>
      </a-layout-content>

      <a-layout-footer style="text-align: center">
        XJTU SE 2022 Created&ensp;by&ensp;GROUP&ensp;
        <span style="color:orangered;">
          <b>XJTU-07</b>
        </span>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
////////////////////////////////////////////
import {reactive, ref} from "vue";
import {
  post, setLocalToken,
  get,
  del,
  getBlob,
  tip,
  removeLocalToken,
  getLocalToken,
} from "@/common";
import {useRouter} from "vue-router";
import {message} from "ant-design-vue";
////////////////////////////////////////////
const router = useRouter();
const goConsultRecord = () => {
  router.push({path: "/student/ConsultRecord"});
};

const goVisitManage = () => {
  router.push({path: "/student/VisitRecord"});
};

const goOrderFirstVisit = () => {
  router.push({path: "/student/OrderFirstVisit"});
};

goOrderFirstVisit();


//获得当前用户
const currUser = ref({});

const getCurrUser = () => {
  get("/curr_user/get_curr-user", {}, {loading: false}).then((res) => {
    currUser.value = res.data;
    console.log("当前用户");
    console.log(currUser.value);
    getAvatar();
  });
};
getCurrUser();

//获得头像
const currImageUrl = ref("");
const getAvatar = () => {
  if (!currUser.value || !currUser.value.avatar) {
    return;
  }
  console.log("开始获取头像")
  getBlob(
      "/avatar/" + currUser.value.avatar,
      {},
      {loading: false}
  ).then((blob) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      currImageUrl.value = reader.result;
    });
    reader.readAsDataURL(blob);
  });
};

//头像文件与可见控制
const avatarFile = ref(null);
const imageUrl = ref("");
const visible = ref(false);


//打开头像上传弹窗
const setAvatar = () => {
  visible.value = true;
};

//控制头像预览图逻辑
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

//头像上传框逻辑控制
const handleChange = (info) => {
  avatarFile.value = info.file;
  // previewImage.value = getBase64(info.file);
  // previewVisible = true;
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    imageUrl.value = reader.result;
  });
  reader.readAsDataURL(info.file);
};

//预览图处理
const handlePreview = async file => {
  if (!file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name
}

//预览图处理，采用Base64算法对图片进行处理
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = error => reject(error);
  });
}

//执行头像上传
const execUpload = () => {
  const token = getLocalToken();
  console.log("执行头像上传，携带Token :");
  console.log(token);
  if (!avatarFile.value) {
    tip.error("请选择头像！");
    return;
  }
  const formData = new FormData();
  formData.append("avatar", avatarFile.value);
  post("/avatar/setavatar", formData).then((res) => {
    tip.success("头像设置成功！");
    visible.value = false;
    getCurrUser();
  });
};

//基础功能菜单栏控制
const selectCurrUser = ({item, key, selectedKeys}) => {
  switch (key) {
    case "exit": //退出系统
      removeLocalToken();
      tip.success("您已成功退出系统，请重新登录！");
      router.push({path: "/"});
      break;

    case "password": //修改密码简易版
      router.push({path: "/security/UpdatePassword"});
      break;
  }
};

const collapsed = ref(false);
////////////////////////////////////////////


////////////////////////////////////////////
</script>

<style>
.logo {
  height: 60px;
  margin: 16px;
  background: lightyellow;
}

.site-layout .site-layout-background {
  background: #fff;
}

[data-theme="dark"] .site-layout .site-layout-background {
  background: #141414;
}
</style>